package com.ruoyi.servie.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.servie.param.MailAttachment;
import com.ruoyi.servie.param.MailParam;
import com.ruoyi.servie.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
@Slf4j
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Override
    public void sendMail(MailParam mailParam) throws MessagingException {
        log.info("发送邮件：{}", mailParam.getText());
        mailSender.setHost(mailParam.getMailHost());
        mailSender.setUsername(mailParam.getMailUserName());
        mailSender.setPassword(mailParam.getMailPassword());
        mailSender.setDefaultEncoding("UTF-8");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        Boolean ismultipart = true;
        if(StringUtils.isEmpty(mailParam.getMailAttachments()) || mailParam.getMailAttachments().size()==0){
            ismultipart = false;
        }
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,ismultipart);
        mimeMessageHelper.setFrom(mailParam.getMailFromUserName());

        mimeMessageHelper.setSubject(mailParam.getSubject());

        mimeMessageHelper.setText(mailParam.getText(), mailParam.getIsHtml());

        mimeMessageHelper.setTo(mailParam.getMailToUserName());
        if(ismultipart){
            List<MailAttachment> mailAttachments = mailParam.getMailAttachments();
            FileSystemResource fileSystemResource = null;
            for (MailAttachment mailAttachment: mailAttachments) {
                fileSystemResource = new FileSystemResource(mailAttachment.getFile());
                if(StringUtils.isBlank(mailAttachment.getAttachmentFilename())){
                    mailAttachment.setAttachmentFilename(fileSystemResource.getFilename());
                }
                mimeMessageHelper.addAttachment(mailAttachment.getAttachmentFilename(), fileSystemResource);
            }
        }
        //发送邮件
        mailSender.send(mimeMessage);
        log.info("发送邮件Success");
    }
}
